<template>
  <div class="p-4">
    <BasicTable @register="tableRegister">
      <template #toolbar>
        <Space size="middle">
          <Tooltip v-if="hasPermission('system-user-add')">
            <template #title>
              <span>{{ ADD }}</span>
            </template>
            <SvgIcon style="cursor: pointer" name="plus" @click="openAddModal" />
          </Tooltip>
          <Tooltip v-if="hasPermission('system-user-change-role')">
            <template #title>
              <span>{{ '分配角色' }}</span>
            </template>
            <SvgIcon name="association" @click="openAssociateModal" style="cursor: pointer" />
          </Tooltip>
        </Space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'avatar'">
          <Avatar :size="40" :src="record.avatar">
            {{ record.username.substring(0, 1) }}
          </Avatar>
        </template>
        <template v-if="column.key === 'gender'">
          <Tag
            v-if="record.gender"
            :color="record.gender === GenderValueEnum.MALE ? 'success' : 'processing'"
          >
            {{ transformGender(record.gender) }}
          </Tag>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                tooltip: EDIT,
                icon: 'edit|svg',
                onClick: openUpdateModal.bind(null, record),
                auth: 'system-user-update',
              },
              {
                tooltip: '分配角色',
                icon: 'association|svg',
                onClick: openSingleAssociateModal.bind(null, record),
                auth: 'system-user-change-role',
              },
              {
                tooltip: DELETE,
                icon: 'delete|svg',
                popConfirm: {
                  title: `确定要删除用户：${record.username}？`,
                  okText: SURE,
                  cancelText: CANCEL,
                  confirm: handleDel.bind(null, record),
                },
                auth: 'system-user-change-role',
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <SaveModal @register="createUserModalRegister" @on-ok="onOk" />
    <AssignRoleModal @register="associateRoleModalRegister" @on-ok="onOk" />
  </div>
</template>

<script lang="ts" setup>
  import { unref } from 'vue';
  import { Avatar, Tooltip, Space, Tag } from 'ant-design-vue';
  import { isArray, isEmpty } from 'lodash-es';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { SvgIcon } from '/@/components/Icon';
  import { ADD, EDIT, DELETE, SURE, CANCEL, ACTION } from '/@/constant';

  import SaveModal from './components/save-modal.vue';
  import AssignRoleModal from './components/assign-role-modal.vue';
  import { columns, getFormConfig } from '/@/views/system/user/schema';
  import { getList, del } from './api';
  import { FormTypeEnum } from '/@/enums/formTypeEnum';
  import { FormData } from '/@/model/FormData';
  import { UserListModel } from './model';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { GenderValueEnum, transformGender } from '/@/enums/genderEnum';

  const { createMessage } = useMessage();
  const { hasPermission } = usePermission();

  const [tableRegister, { reload, getSelectRows }] = useTable({
    title: '用户列表',
    columns,
    api: getList,
    rowKey: 'id',
    showTableSetting: true,
    useSearchForm: true,
    formConfig: getFormConfig(),
    rowSelection: {
      type: 'checkbox',
    },
    handleSearchInfoFn: (searchInfo) => {
      return searchInfo;
    },
    actionColumn: {
      width: 160,
      title: ACTION,
      dataIndex: 'action',
    },
  });

  // 新增用户
  const [createUserModalRegister, { openModal: openAddUserModal }] = useModal();
  const openAddModal = () => {
    const data: FormData<UserListModel> = {
      type: FormTypeEnum.ADD,
    };
    openAddUserModal(true, data);
  };
  const openUpdateModal = (obj: UserListModel) => {
    const data: FormData<UserListModel> = {
      type: FormTypeEnum.EDIT,
      obj,
    };
    openAddUserModal(true, data);
  };
  const onOk = () => {
    reload();
  };
  // 删除用户
  const handleDel = async (record: Recordable) => {
    const { id } = unref(record);
    await del({ id });
    await reload();
  };

  // 关联角色
  const [associateRoleModalRegister, { openModal: openAssociateRoleModal }] = useModal();
  const openSingleAssociateModal = async (obj: UserListModel) => {
    openAssociateRoleModal(true, unref(obj));
  };
  const openAssociateModal = () => {
    const selected: UserListModel[] = getSelectRows();
    if (isArray(selected) && !isEmpty(selected)) {
      openAssociateRoleModal(true, selected);
    } else if (isArray(selected) && isEmpty(selected)) {
      createMessage.warn('请选择要修改角色的用户');
    }
  };
</script>

<style scoped></style>
